package com.hzx.demo.helper;

import android.hardware.Camera;
import android.view.SurfaceView;

import java.io.File;
import java.io.IOException;

/**
 * 拥有打开摄像头与关闭摄像头的方法
 * Created by ldkxingzhe on 2016/6/28.
 */
public class CameraModule {
    @SuppressWarnings("unused")
    private static final String TAG = "CameraModule";
    protected Camera mCamera;

    /**
     * 打开摄像头
     * @param isFrontCamera   true -- 是前置摄像头
     * @param previewSurface  预览显示的SurfaceView, previewSurface must has SurfaceHolder
     */
    public void openCamera(boolean isFrontCamera, SurfaceView previewSurface){
        mCamera = Camera.open(getCameraIndex(isFrontCamera));
        if(mCamera == null) throw new IllegalStateException("mCamera is null");

        if(!isFrontCamera){
            mCamera.setDisplayOrientation(90);
        }
        try {
            mCamera.setPreviewDisplay(previewSurface.getHolder());
        } catch (IOException e) {
            throw new IllegalArgumentException("previewSurface must has a valid surfaceHolder");
        }
        mCamera.startPreview();
        Camera.Parameters parameters = mCamera.getParameters();
        diyCameraParameters(parameters);
        mCamera.setParameters(parameters);
    }

    /**
     * 是否是前置摄像头
     * @param isFrontCamera  true -- 是前置摄像头
     * @return
     */
    public int getCameraIndex(boolean isFrontCamera){
        int resultIndex = -1;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        int cameraNum = Camera.getNumberOfCameras();
        for(int i = 0; i < cameraNum; i++){
            Camera.getCameraInfo(i, cameraInfo);
            int cameraID = isFrontCamera ? Camera.CameraInfo.CAMERA_FACING_FRONT
                    : Camera.CameraInfo.CAMERA_FACING_BACK;
            if(cameraInfo.facing == cameraID){
                resultIndex = i;
                break;
            }
        }
        return resultIndex;
    }

    /** 照相机的参数自定义 */
    protected void diyCameraParameters(Camera.Parameters parameters){

    }

    /**
     * 关闭摄像头
     */
    public void stopPreviewAndCloseCamera(){
        if(mCamera == null) return;
        mCamera.stopPreview();
        mCamera.release();
    }

    protected void makeSureFileFine(String filePath) {
        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
    }
}
